<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>模拟 Cascader（多级菜单）</title>
  </head>
  <style>
    ul > li {
      width: 80px;
      list-style: none;
      border: 1px solid;
    }

    .slectItem {
      position: relative;
    }

    .item1 {
      padding: 0px;
      position: absolute;
      top: 0;
      left: 0;
    }

    .item2 {
      padding: 0px;
      position: absolute;
      top: 0;
      left: 80px;
    }
  </style>
  <body>
    <h3>点击一级菜单出现2级菜单</h3>
    <div class="slectItem">
      <ul class="item1"></ul>
      <ul class="item2"></ul>
    </div>

    <script>
      const data = [
        {
          name: '北京',
          children: [
            {
              name: '丰台区',
            },
            {
              name: '石景山区',
            },
            {
              name: '海淀区',
            },
            {
              name: '东城区',
            },
            {
              name: '西城区',
            },
            {
              name: '朝阳区',
            },
          ],
        },
        {
          name: '上海',
          children: [
            {
              name: '浦东新区',
            },
            {
              name: '徐汇区',
            },
            {
              name: '长宁区',
            },
            {
              name: '静安区',
            },
            {
              name: '黄浦区',
            },
            {
              name: '虹口区',
            },
          ],
        },
        {
          name: '广州',
          children: [
            {
              name: '天河区',
            },
            {
              name: '越秀区',
            },
            {
              name: '海珠区',
            },
            {
              name: '荔湾区',
            },
            {
              name: '白云区',
            },
            {
              name: '黄埔区',
            },
          ],
        },
      ]

      // 获取 UL 元素
      const ul1 = document.querySelector('.item1')
      const ul2 = document.querySelector('.item2')

      // 使用 JavaScript 循环来动态创建 LI 元素
      for (let i = 0; i < data.length; i++) {
        const li = document.createElement('li') // 创建 li 元素
        li.addEventListener('click', function () {
          // 先清空二级菜单
          ul2.innerHTML = ''
          // 循环展示二级菜单
          data[i].children.forEach(item => {
            const li = document.createElement('li')
            li.textContent = item.name
            ul2.appendChild(li)
          })
        })
        // 设置 li 元素的文本内容
        li.textContent = data[i].name
        // 将 li 元素添加到 ul 中
        ul1.appendChild(li)
      }
    </script>
  </body>
</html>
